<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1{
            width: 100px;
            height: 100px;
            position: absolute;
            background: red;
        }
        .box2{
            width: 100px;
            height: 100px;
            left: 400px;
            position: absolute;
            background: blue;
        }
    </style>
</head>
<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
        var box1Ele = document.querySelector(".box1");
        var box2Ele = document.querySelector(".box2");
        box1Ele.onmousedown = function(e){
                var e = e || window.event;
                var x = e.clientX - this.offsetLeft;
                var y = e.clientY - this.offsetTop;
                box1Ele.onmousemove = function(e){
                    var e = e || window.event;
                //   if(  Math.abs( ( box2Ele.offsetLeft - box1Ele.offsetLeft))<box1Ele.offsetWidth){
                //       console.log("横轴碰撞上了");
                //   }
                    
                //   if(Math.abs(( box2Ele.offsetTop - box1Ele.offsetTop))<box1Ele.offsetHeight){
                //     console.log("Y轴上碰撞了");
                //   }
                // 检测碰撞方式一；
                // if(Math.abs( ( box2Ele.offsetLeft - box1Ele.offsetLeft))<box1Ele.offsetWidth && Math.abs(( box2Ele.offsetTop - box1Ele.offsetTop))<box1Ele.offsetHeight){
                //     console.log("碰撞了");
                // }
                // 检测碰撞方式二：
                var Amin = box1Ele.offsetLeft;
                var Amax = box1Ele.offsetLeft + box1Ele.offsetWidth;
                var Bmin = box2Ele.offsetLeft;
                var Bmax = box2Ele.offsetLeft +box2Ele.offsetWidth;
                if(Amax>Bmin && Amin<Bmax){
                    console.log("横轴碰撞了");
                }


                    var xx = e.clientX - x;
                    var yy = e.clientY - y;
                    this.style.left = xx + "px";
                    this.style.top = yy + "px";
                }
                document.onmouseup = function(){
                    box1Ele.onmousemove = "";
                    box1Ele.style.zIndex = 1;
                }
            }



    </script>
</body>
</html>